from django.http import JsonResponse
from django.shortcuts import render, HttpResponse, redirect
from django.views.decorators.csrf import csrf_exempt
from web.forms.wiki import WikiModelForm
from django.urls import reverse
from web import models
from utils.encrypt import uid
from utils.tencent.cos import upload_file

"""
wiki管理
1. 表结构设计
ID  标题  内容  项目id    父id

2. 快速开发
3. 应用markdown组件
4. 基于腾讯cos做上传
"""


def wiki(request, project_id):
    """wiki首页"""
    wiki_id = request.GET.get('wiki_id')
    if not wiki_id or not wiki_id.isdecimal():
        return render(request, 'wiki.html')

    """查看文章详细"""
    wiki_obj = models.Wiki.objects.filter(id=wiki_id, project_id=project_id).first()

    return render(request, 'wiki.html', {'wiki_obj': wiki_obj})


def wiki_add(request, project_id):
    """wiki添加"""
    if request.method == 'GET':
        form = WikiModelForm(request=request)
        return render(request, 'wiki_form.html', {'form': form})
    form = WikiModelForm(request, request.POST)
    if form.is_valid():
        # 判断用户是否选择父文章
        if form.instance.parent:
            form.instance.depth = form.instance.parent.depth + 1
        else:
            form.instance.depth = 1
        form.instance.project = request.tracer.project
        form.save()
        url = reverse('wiki', kwargs={'project_id': project_id})
        return redirect(url)
    return render(request, 'wiki_form.html', {'form': form})


def wiki_catalog(request, project_id):
    """获取wiki目录"""
    data = models.Wiki.objects.filter(
        project=request.tracer.project).values('id', 'title', 'parent_id').order_by('depth', 'id')

    return JsonResponse({"status": True, "data": list(data)})


"""
作业:
    多级目录
    修改 & 删除
    
    mdeditor
    - TextArea->editor
    上传图片 + cos
"""


def wiki_edit(request, project_id, wiki_id):
    """编辑wiki"""
    wiki_obj = models.Wiki.objects.filter(project_id=project_id, id=wiki_id).first()
    if not wiki_obj:
        url = reverse('wiki', kwargs={'project_id': project_id})
        return redirect(url)
    if request.method == 'GET':
        form = WikiModelForm(request, instance=wiki_obj)
        return render(request, 'wiki_form.html', {"form": form})
    form = WikiModelForm(request, data=request.POST, instance=wiki_obj)
    if form.is_valid():
        # 判断用户是否选择父文章
        if form.instance.parent:
            form.instance.depth = form.instance.parent.depth + 1
        else:
            form.instance.depth = 1
        form.instance.project = request.tracer.project
        form.save()
        url = reverse('wiki', kwargs={'project_id': project_id})
        preview_url = f"{url}?wiki_id={wiki_id}"
        return redirect(preview_url)
    return render(request, 'wiki_form.html', {"form": form})


def wiki_delete(request, project_id, wiki_id):
    """删除wiki"""
    models.Wiki.objects.filter(project_id=project_id, id=wiki_id).delete()
    url = reverse('wiki', kwargs={'project_id': project_id})
    return redirect(url)


@csrf_exempt
def wiki_upload(request, project_id):
    """Markdown上传图片"""
    result = {
        'success': 0,
        'message': None,
        'url': None
    }
    img_obj = request.FILES.get('editormd-image-file')
    if not img_obj:
        result['message'] = '文件不存在'
        return JsonResponse(result)
    # 图片格式
    ext = img_obj.name.rsplit('.')[-1]
    key = f"{uid(request.tracer.user.mobile_phone)}.{ext}"
    # 文件对象上传到当前项目的桶中
    img_url = upload_file(
        request.tracer.project.bucket,
        request.tracer.project.region,
        img_obj,
        key
    )
    result['success'] = 1
    result['url'] = img_url
    return JsonResponse(result)


"""
1. 创建项目时, 创建桶 实现cors跨域
2. 临时密钥上传文件功能
3. 创建文件夹, 列表页面
4. 文件管理
    文件夹管理
    文件上传
"""